﻿function ChangeSushiName(sushiId) {
    var sushiName = document.getElementById('sushi-name-' + sushiId);
    $.ajax({
        url: "Menu/ChangeSushiName",
        type: "POST",
        dataType: "text",
        data: JSON.stringify({
            "Id": sushiId,
            "Name": sushiName.value
        }),
        contentType: "application/json; charset=utf-8",
        beforeSend: function () {
            sushiName.style.backgroundColor = "#FFA";
        },
        error: function () {
            sushiName.style.backgroundColor = "#FAA";
        },
        success: function (response) {
            if (response == "Ok") {
                sushiName.style.backgroundColor = "#AFA";
            } else {
                sushiName.style.backgroundColor = "#FAA";
            }
        }
    });
}

function ChangePrice(sushiId) {
    var sushiPriceContainer = document.getElementById('sushi-price-' + sushiId);
    $.ajax({
        url: "Menu/ChangePrice",
        type: "POST",
        dataType: "text",
        data: JSON.stringify({
            "Id": sushiId,
            "Price": parseInt(sushiPriceContainer.value)
        }),
        contentType: "application/json; charset=utf-8",
        beforeSend: function () {
            sushiPriceContainer.style.backgroundColor = "#FFA";
        },
        error: function () {
            sushiPriceContainer.style.backgroundColor = "#FAA";
        },
        success: function () {
            sushiPriceContainer.style.backgroundColor = "#AFA";
        }
    });
}

function ChangeCategoryName(categoryId) {
    var category = document.getElementById('category_name_' + categoryId);
    $.ajax({
        url: "Menu/ChangeCategoryName",
        type: "POST",
        dataType: "text",
        data: JSON.stringify({
            "Id": categoryId,
            "Name": category.value
        }),
        contentType: "application/json; charset=utf-8",
        beforeSend: function () {
            category.style.backgroundColor = "#FFA";
        },
        error: function () {
            category.style.backgroundColor = "#FAA";
        },
        success: function (response) {
            if (response == "Ok") {
                category.style.backgroundColor = "#AFA";
            } else {
                category.style.backgroundColor = "#FAA";
            }
        }
    });
}

function CreateCategory() {
    var newCategory = document.getElementById("new-category-name");
    if (newCategory != null) {
        $.ajax({
            url: "Menu/CreateNewCategory",
            type: "POST",
            dataType: "json",
            data: JSON.stringify({
                "Id": 0,
                "Name": newCategory.value
            }),
            contentType: "application/json; charset=utf-8",
            beforeSend: function () {
                newCategory.style.backgroundColor = "#FFA";
            },
            error: function () {
                newCategory.style.backgroundColor = "#FAA";
            },
            success: function (data) {
                var element = document.getElementById("new-category");

                var endDiv = document.createElement("div");
                endDiv.setAttribute("class", "end");
                endDiv.innerText = "";

                //just created category
                var category = document.createElement("div");
                category.setAttribute("class", "category");
                category.setAttribute("id", "category-" + data.Id);

                var categoryName = document.createElement("div");
                categoryName.setAttribute("class", "category-name");

                var categoryInput = document.createElement("input");
                categoryInput.setAttribute("type", "text");
                categoryInput.setAttribute("onblur", "ChangeCategoryName(" + data.Id + ")");
                categoryInput.setAttribute("value", data.Name);

                //New sushi
                var newSushi = document.createElement("div");
                newSushi.setAttribute("class", "sushi-admin");
                newSushi.setAttribute("id", "new-sushi-" + data.Id);
                newSushi.style.backgroundColor = "white";

                var newSushiInfo = document.createElement("div");
                newSushiInfo.setAttribute("class", "sushi-info-admin");

                var labelName = document.createElement("span");
                labelName.setAttribute("class", "sushi-name-label-admin");
                labelName.innerHTML = "Название: ";

                var sushiNameInput = document.createElement("input");
                sushiNameInput.setAttribute("type", "text");
                sushiNameInput.setAttribute("class", "sushi-name-admin");
                sushiNameInput.setAttribute("id", "new-sushi-name-" + data.Id);
                sushiNameInput.setAttribute("placeholder", "Name");

                var labelPrice = document.createElement("span");
                labelPrice.setAttribute("class", "sushi-price-label-admin");
                labelPrice.innerHTML = "Цена: ";

                var sushiPriceInput = document.createElement("input");
                sushiPriceInput.setAttribute("type", "text");
                sushiPriceInput.setAttribute("class", "sushi-price-admin");
                sushiPriceInput.setAttribute("id", "new-sushi-price-" + data.Id);
                sushiPriceInput.setAttribute("placeholder", "Price");

                var newSushiButton = document.createElement("button");
                newSushiButton.setAttribute("type", "button");
                newSushiButton.setAttribute("onclick", "CreateSushi(" + data.Id + ")");
                newSushiButton.innerHTML = "Создать суши";

                newSushiInfo.appendChild(labelName);
                newSushiInfo.appendChild(sushiNameInput);
                newSushiInfo.appendChild(labelPrice);
                newSushiInfo.appendChild(sushiPriceInput);
                newSushiInfo.appendChild(newSushiButton);

                newSushi.appendChild(newSushiInfo);
                categoryName.appendChild(categoryInput);
                category.appendChild(categoryName);
                category.appendChild(newSushi);

                $(element).before(category);
                $(element).before(endDiv);

                newCategory.value = "";
                newCategory.style.backgroundColor = "#FFF";
            }
        });
    }
}

function DeleteCategory(categoryId, categoryName) {
    if (confirm("Вы хотите удалить категорию \"" + categoryName + "\" и все блюда, содержащиеся в ней?"))
        $.ajax({
            url: "Menu/DeleteCategory",
            type: "POST",
            dataType: "text",
            data: JSON.stringify({
                Id: categoryId
            }),
            contentType: "application/json; charset=utf-8",
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText + "\n" + thrownError);
            },
            success: function (data) {
                if (data) {
                    alert(data);
                } else {
                    $("#category-" + categoryId).hide(500);
                }
            }
        });
}

function CreateSushi(categoryId) {
    var nameElement = document.getElementById('new-sushi-name-' + categoryId);
    var priceElement = document.getElementById('new-sushi-price-' + categoryId);
    var name = nameElement.value;
    var price = parseInt(priceElement.value);
    var allFieldsAreFilled = true;

    if (!name) {
        alert("Необходимо выбрать название");
        allFieldsAreFilled = false;
    }
    else if (!price) {
        alert("Необходимо назначить цену");
        allFieldsAreFilled = false;
    }

    if (allFieldsAreFilled) {
        $.ajax({
            url: "Menu/CreateSushi",
            type: "POST",
            dataType: "json",
            data: JSON.stringify({
                "Id": 0,
                "Name": name,
                "Price": price,
                "SmallPhoto": NaN,
                "ParentCategory": categoryId
            }),
            contentType: "application/json; charset=utf-8",
            beforeSend: function () {
                nameElement.style.backgroundColor = "#FFA";
                priceElement.style.backgroundColor = "#FFA";
            },
            success: function (data) {

                var element = document.getElementById("new-sushi-" + categoryId);

                var newSushi = document.createElement("div");
                newSushi.setAttribute("class", "sushi-admin");
                newSushi.setAttribute("draggable", "true");
                newSushi.setAttribute("onmousedown", "handlerMouseDown(this, event)");
                newSushi.setAttribute("id", "sushi-" + data.Id);
                newSushi.style.backgroundImage = "url('/Content/i/" + data.SmallPhoto + "')";

                var sushiInfo = document.createElement("div");
                sushiInfo.setAttribute("class", "sushi-info-admin");

                var labelName = document.createElement("span");
                labelName.setAttribute("class", "sushi-name-label-admin");
                labelName.innerHTML = "Название: ";

                var sushiName = document.createElement('input');
                sushiName.setAttribute("type", "text");
                sushiName.setAttribute("class", "sushi-name-admin");
                sushiName.setAttribute("id", "sushi-name-" + data.Id);
                sushiName.setAttribute("onblur", "ChangeSushiName(" + data.Id + ")");
                sushiName.setAttribute("value", data.Name);

                var labelPrice = document.createElement("span");
                labelPrice.setAttribute("class", "sushi-price-label-admin");
                labelPrice.innerHTML = "Цена: ";

                var sushiPrice = document.createElement('input');
                sushiPrice.setAttribute("type", "text");
                sushiPrice.setAttribute("class", "sushi-price-admin");
                sushiPrice.setAttribute("id", "sushi-price-" + data.Id);
                sushiPrice.setAttribute("onblur", "ChangePrice(" + data.Id + ")");
                sushiPrice.setAttribute("value", data.Price);

                var photoForm = document.createElement("form");
                photoForm.setAttribute("action", "/admin/Menu/UploadImage");
                photoForm.setAttribute("enctype", "multipart/form-data");
                photoForm.setAttribute("method", "post");

                var hiddenId = document.createElement("input");
                hiddenId.setAttribute("type", "text");
                hiddenId.setAttribute("hidden", "hidden");
                hiddenId.setAttribute("name", "SushiId");
                hiddenId.setAttribute("value", data.Id);

                var inputPhoto = document.createElement("input");
                inputPhoto.setAttribute("name", "SushiPhoto");
                inputPhoto.setAttribute("type", "file");

                var buttonUploadPhoto = document.createElement("button");
                buttonUploadPhoto.setAttribute("type", "submit");
                buttonUploadPhoto.innerHTML = "Загрузить фотографию"; //"Upload photo"

                var buttonDeleteSushi = document.createElement("button");
                buttonDeleteSushi.setAttribute("onclick", "DeleteSushi(" + data.Id + ", '" + data.Name + "')");
                buttonDeleteSushi.innerHTML = "Удалить " + data.Name; // "Delete SushiName"

                photoForm.appendChild(hiddenId);
                photoForm.appendChild(inputPhoto);
                photoForm.appendChild(buttonUploadPhoto);

                sushiInfo.appendChild(labelName);
                sushiInfo.appendChild(sushiName);
                sushiInfo.appendChild(labelPrice);
                sushiInfo.appendChild(sushiPrice);
                sushiInfo.appendChild(photoForm);
                sushiInfo.appendChild(buttonDeleteSushi);
                newSushi.appendChild(sushiInfo);

                $(element).before(newSushi);

                nameElement.style.backgroundColor = "#FFF";
                priceElement.style.backgroundColor = "#FFF";
                nameElement.value = "";
                priceElement.value = "";
            }
        }
    );
    }
}

function DeleteSushi(sushiId, sushiName) {
    if (confirm("Вы хотите удалить " + sushiName + "?")) {
        $.ajax({
            url: "Menu/DeleteSushi",
            type: "POST",
            dataType: "text",
            data: JSON.stringify({
                Id: sushiId
            }),
            contentType: "application/json; charset=utf-8",
            error: function (xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\n" + xhr.responseText);
            },
            success: function (data) {
                if (data) {
                    alert(data);
                } else {
                    $("#sushi-" + sushiId).hide(500);
                }
            }
        })
    }
}

var startX, startY;
var dragObject;
var arrSushi, arrIndex;
var placeObject;
var list;
//functions to be saved and restored while draging objects
//
var functionOnDragStart, functionOnSelectStart; 

function handlerMouseDown(o, e) {
    e = crospplatformEvent(e);
    dragObject = o.offsetParent;
    dragObject.style.zIndex = 1000;
    startX = e.pageX;
    startY = e.pageY;
    document.ondragstart = function () { return false };
    document.body.onselectstart = function () { return false };
    return false;
}

function startingFunction() {
    arrSushi = new Array();
    arrIndex = 0;
    functionOnDragStart = document.ondragstart;
    functionOnSelectStart = document.body.onselectstart;
    //list = document.getElementById("asdf");

    document.onmouseup = function () {
        if (dragObject && placeObject) {
            changeSushiPlace(dragObject.offsetParent.sushiId, placeObject.sushiId);
        }

        dragObject.style.left = '0px';
        dragObject.style.top = '0px';
        dragObject.style.zIndex = 0;
        dragObject = null;

        document.ondragstart = functionOnDragStart;
        document.body.onselectstart = functionOnSelectStart;
    }
    document.onmousemove = function (e) {
        if (dragObject) {
            e = crospplatformEvent(e);

            dragObject.style.left = (e.pageX - startX) + 'px';
            dragObject.style.top = (e.pageY - startY) + 'px';

            getMovableObject(e);
        }
    }
}

function crospplatformEvent(e) {
    if (!e) e = window.event;
    if (!e.pageX && e.clientX) {
        var html = document.documentElement;
        var body = document.body;
        e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
        e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
    }
    return e;
}

function addSushiToArray(sushiId) {
    var obj = document.getElementById("sushi-admin-cover-" + sushiId);
    obj.sushiId = sushiId;
    arrSushi[sushiId] = obj;
}

function getMovableObject(e) {
    placeObject = null;

    for (var i = 0; i < arrSushi.length; i++) {

        var elem = arrSushi[i];

        if (elem
            && elem.id != dragObject.offsetParent.id
            && e.pageX > elem.offsetLeft
            && e.pageX < elem.offsetLeft + elem.offsetWidth
            && e.pageY > elem.offsetTop
            && e.pageY < elem.offsetTop + elem.offsetHeight) {

            placeObject = elem;
        }
    }
}

function changeSushiPlace(dragSushiId, placeSushiId) {
    alert("drag: " + dragSushiId + "\nplace: " + placeSushiId);
    if (dragSushiId && placeSushiId) {
        $.ajax({
            url: "Menu/ChangeSushiPlace",
            type: "POST",
            dataType: "json",
            data: JSON.stringify({
                dragId: parseInt(dragSushiId),
                placeId: parseInt(placeSushiId)
            }),
            contentType: "application/json; charset=utf-8",
            error: function () {
                alert("Error on changing sushi places");
            },
            success: function (data) {
                alert("Данные переданы верно: \ndragId - " + data.dragId + "\nplaceId - " + placeId);
            }
        });
    }
}